package javabase.demo02;

import java.util.*;

public class CollectionsPractice {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(2);
        numbers.add(8);
        numbers.add(1);
        numbers.add(9);


        System.out.println("原始列表: " + numbers);

        // 排序
        Collections.sort(numbers);
        System.out.println("排序后: " + numbers);

        // 逆序
        Collections.reverse(numbers);
        System.out.println("逆序后: " + numbers);

        // 随机排序
        Collections.shuffle(numbers);
        System.out.println("随机排序后: " + numbers);

        // 二分查找 (需要先排序)
        Collections.sort(numbers);
        int index = Collections.binarySearch(numbers, 5);
        System.out.println("5的索引: " + index);

        // 最大值和最小值
        System.out.println("最大值: " + Collections.max(numbers));
        System.out.println("最小值: " + Collections.min(numbers));

        // 填充
        Collections.fill(numbers, 0);
        System.out.println("填充后: " + numbers);


        // 创建线程安全的集合
        List<String> syncList = Collections.synchronizedList(new ArrayList<>());
        Set<String> syncSet = Collections.synchronizedSet(new HashSet<>());
        Map<String, Integer> syncMap = Collections.synchronizedMap(new HashMap<>());

        // 不可修改的集合
        List<String> unmodifiableList = Collections.unmodifiableList(Arrays.asList("A", "B", "C"));
        Set<String> unmodifiableSet = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("A", "B", "C")));
        Map<String, Integer> unmodifiableMap = Collections.unmodifiableMap(new HashMap<String, Integer>() {{
            put("A", 1);
            put("B", 2);
        }});

        // 尝试修改会抛出UnsupportedOperationException
        try {
            unmodifiableList.add("D");
        } catch (UnsupportedOperationException e) {
            System.out.println("不能修改不可修改集合: " + e.getMessage());
        }

        // 单元素集合
        List<String> singletonList = Collections.singletonList("OnlyOne");
        Set<String> singletonSet = Collections.singleton("OnlyOne");
        Map<String, Integer> singletonMap = Collections.singletonMap("key", 1);

        System.out.println("单元素列表: " + singletonList);
        System.out.println("单元素集合: " + singletonSet);
        System.out.println("单元素映射: " + singletonMap);
    }
}
